package com.dxy.md.generator;


import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collections;


/**
 * 代码生成类
 * Created by Xianyue Dang on 2021/8/24
 */
@Component
public class MybatisPlusGenerator {

    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.driver-class-name}")
    private String dbDriver;
    @Value("${spring.datasource.username}")
    private String dbUsername;
    @Value("${spring.datasource.password}")
    private String dbPassword;


    /**
     * 生成代码
     *
     * @param projectPath   项目路径
     * @param parentPackage 父包名称
     * @param tables        表
     * @param author        作者
     * @param isSwagger     是否开启swagger
     */
    public void generate(String projectPath, String parentPackage, String[] tables, String[] tablePrefix, String author, boolean isSwagger) {
        FastAutoGenerator.create(dbUrl, dbUsername, dbPassword)
                .globalConfig(builder -> {
                    builder.author(author) // 设置作者
//                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir(String.format("%s%s", projectPath, "/java")); // 指定输出目录
                    if (isSwagger) {
                        builder.enableSwagger();
                    }
                })
                .packageConfig(builder -> {
                    builder.parent(parentPackage) // 设置父包名
                            .entity("model.po")
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, String.format("%s%s", projectPath, "/resources/mapper"))); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude(tables) // 设置需要生成的表名
                            .addTablePrefix(tablePrefix)
                            .serviceBuilder().formatServiceFileName("%sService")
                            .entityBuilder().formatFileName("%sPO") // 设置过滤表前缀
                            .enableLombok();
                })
                .execute();
    }


}

